/* eslint-disable jsx-a11y/label-has-associated-control */
import { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { isEmpty, Tabs, class_esy, isArray, Button, Toast, RightOutlined, EyeHideOutlined, EyeOutlined, WarnCircleFilled } from 'esy-ui';
import { Empty, Header, Img } from '@/components';
import { postUserBindBank, postWithdrawlConfig, postWithdrawlCreateOrder } from '@/services';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import sltPng from '@/assets/images/common/deposit_check.png';
import { deposit_input_cn } from '@/styles/esy-ui';
import { useFormatText, useNavigation } from '@/hooks';
import firePng from '@/assets/images/common/tag_fire.png';
import BindListDialog from './BindListDialog';

// 取款方式
const types = Object.freeze({
  12: 0, // 银行卡
  11: 1, // USDT
  13: 2, // 支付宝
});

const list = [
  {
    Id: 3,
    Title: '在线提款',
    Describe: '',
    TitleImage: '',
    DescribeImage: '',
    AcTitleImage: '',
    AcDescribeImage: '',
    Pwtype: 0,
    SubList: [
      {
        Id: 6,
        MtypeId: 3,
        Title: '支付宝',
        Describe: '',
        TitleImage: '',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 13,
            StypeId: 6,
            ModeName: '支付宝',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 20000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 7,
        MtypeId: 3,
        Title: '银行卡',
        Describe: '',
        TitleImage: '',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 12,
            StypeId: 7,
            ModeName: '银联',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 20000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
    ],
  },
  {
    Id: 3,
    Title: '在线提款',
    Describe: '',
    TitleImage: '',
    DescribeImage: '',
    AcTitleImage: '',
    AcDescribeImage: '',
    Pwtype: 0,
    SubList: [
      {
        Id: 6,
        MtypeId: 3,
        Title: '支付宝',
        Describe: '',
        TitleImage: '',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 13,
            StypeId: 6,
            ModeName: '支付宝',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 20000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 7,
        MtypeId: 3,
        Title: '银行卡',
        Describe: '',
        TitleImage: '',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 12,
            StypeId: 7,
            ModeName: '银联',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 20000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
    ],
  },
  {
    Id: 4,
    Title: '电子钱包提款',
    Describe: '',
    TitleImage: '',
    DescribeImage: '',
    AcTitleImage: '',
    AcDescribeImage: '',
    Pwtype: 1,
    SubList: [
      {
        Id: 8,
        MtypeId: 4,
        Title: 'USDT',
        Describe: '',
        TitleImage: '',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 11,
            StypeId: 8,
            ModeName: 'USDT-TRC20',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 5000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
    ],
  },
];

function RenderTitle(props: any) {
  const { title, isActive } = props;
  return <div className={class_esy(['text-sm font-bold', isActive ? 'text-color-21' : 'text-color-17'])}>{title}</div>;
}

// 单个选择
function RenderItem(props: any) {
  const { Id, checkId, change, TitleImage, Title, ModeName, isThree, ModeId, MinAmount, MaxAmount, IsRecommend, IsHot, text, AmountLimitType, AmountLimitFix } = props;
  let id;
  let title;
  let rangeAmont = '';
  // 三级通道的处理
  if (isThree) {
    // 唯一标识
    id = ModeId;
    // 名称显示
    title = ModeName;
    // 限额处理
    if (AmountLimitType === 1) {
      const btns = AmountLimitFix ? JSON.parse(AmountLimitFix) : null;
      rangeAmont = isArray(btns) ? `${btns[0]}${text('text_52')}~${btns[btns.length - 1]}${text('text_52')}` : '';
    } else {
      rangeAmont = `${MinAmount}
            ${text('text_52')}~${MaxAmount}
            ${text('text_52')}`;
    }
  } else {
    id = Id;
    title = Title;
  }

  return (
    <div className={class_esy([isThree ? 'inline-block' : 'w-1/4'])}>
      <div
        className={class_esy([
          'relative flex flex-col items-center justify-center box-border mx-1 mb-2 p-2 border border-solid rounded cursor-pointer text-xs',
          id === checkId ? 'border-color-21 shadow-sld' : 'border-color-19',
        ])}
        onClick={() => {
          change(id);
        }}
      >
        {isThree && IsRecommend ? (
          <div className='absolute -top-2.5 px-1 -left-1.5 font-bold bg-lg-5 rounded-r-3xl rounded-tl-3xl text-white flex items-center h-5 scale-75'>
            {IsHot ? <Img boxClassName='w-4 h-5' src={firePng} /> : null}
            {text('text_53')}
          </div>
        ) : null}
        {id === checkId ? <Img boxClassName='absolute right-0 top-0 w-4 h-4' src={sltPng} /> : null}
        {isThree ? null : <Img boxClassName='w-7 h-7 mb-2' src={TitleImage} />}
        <div>{title}</div>
        {isThree ? <div className='text-split mt-1 min-h-4'>{rangeAmont}</div> : null}
      </div>
    </div>
  );
}

function RenderContent(props: any) {
  const { data, Token, Name } = props;
  const { text } = useFormatText();
  const { changeState } = useGlobalStore();
  const navigation = useNavigation();
  const [checkId, setCheckId] = useState(data[0]?.Id);
  const [cId, setCId] = useState<number>();
  // 取款金额
  const [amont, setValue] = useState<string>('');
  // 取款地址
  const [addr, setAddr] = useState<string>('--');
  // 银行账号
  const [bank, setBank] = useState<string>('--');
  // 控制取款密码输入框type
  const [iptType, setIptType] = useState('password');
  // 取款密码
  const [psdVal, setPassword] = useState<string>('');
  // U兑换数量
  const [countU, setCountU] = useState('--');
  // 我的绑定信息
  const [bindInfo, setBandInfo] = useState(null);
  // 列表弹窗
  const [dlOpen, setDlOpen] = useState(false);

  console.info(setCountU);

  // 三级通道
  const channels = (data || []).find((its) => its.Id === checkId)?.ChannelList;

  // 当前的通道单个数据
  const channel = channels.find((it) => it.ModeId === cId);

  // 是否是usd
  const isUST = channel?.ModeId === 11;

  // 是否是银行
  const isBank = channel?.ModeId === 12;

  // 获取我的绑定列表
  useEffect(() => {
    if (Token && channel?.ModeId) {
      changeState('isLoading', true);
      postUserBindBank({
        PWType: types[channel?.ModeId],
      })
        .then((res: any) => {
          if (res?.Data) {
            setBandInfo(res?.Data);
            // 银行账号设置
            if (isBank) {
              setBank(res?.Data?.AccountNo);
            } else {
              setAddr(res?.Data?.AccountNo);
            }
          }
        })
        .catch(() => {})
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  }, [Token, changeState, channel?.ModeId, isBank]);

  useEffect(() => {
    if (isArray(data) && !isEmpty(data)) {
      const list = data.find((it) => it.Id === checkId)?.ChannelList || [];
      setCId(list[0]?.ModeId);
    }
  }, [checkId, data]);

  // 切换二级列表
  const change = useCallback((id: number) => {
    setCheckId(id);
    setValue('');
  }, []);

  // 切换通道
  const changeThree = useCallback((id: number) => {
    setCId(id);
    setValue('');
  }, []);

  // 提现
  const onDeposit = () => {
    if (Token && channel?.ModeId && Number(amont) > 0) {
      changeState('isLoading', true);
      postWithdrawlCreateOrder({ ModeID: channel.ModeId, Amount: Number(amont), PWType: types[channel?.ModeId], BindID: 1, FundPassword: psdVal })
        .then(() => {
          Toast.show({ content: text('text_50') });
        })
        .catch(() => {
          // Toast.show({ content: text('text_51') });
        })
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  };

  // 打开列表弹窗
  const onOpen = () => {
    setDlOpen(true);
  };

  // 关闭列表弹窗
  const onClose = useCallback(() => {
    setDlOpen(false);
  }, []);

  // 选择取款地址
  const onSelected = (info) => {
    if (info?.Pwtype === types[12]) {
      setBank(info?.AccountNo);
    } else {
      setAddr(info?.AccountNo);
    }
    onClose();
  };

  // 新增银行账号/新增钱包
  const addBandAccount = () => {
    if (channel?.ModeId) {
      navigation('/band-list');
    }
  };

  if (isEmpty(data) || !isArray(data)) return <Empty />;

  const isSubmit = amont && psdVal && (isBank ? bank : addr);

  return (
    <div className='overflow-y-auto h-full flex flex-col'>
      <div className='flex flex-wrap p-2.5 bg-white'>
        {data.map((it: any, i) => (
          <RenderItem key={it.Id || i} {...it} change={change} checkId={checkId} text={text} />
        ))}
      </div>
      <div className='overflow-x-scroll overflow-y-hidden mt-2.5 bg-white p-2.5'>
        {isArray(channels) ? channels.map((item, idx) => <RenderItem key={item.ModeId || idx} {...item} change={changeThree} isThree checkId={cId} text={text} />) : <Empty />}
      </div>
      <div className='bg-white flex-1 mt-2 pt-2 pb-24 px-3'>
        <form>
          {isUST ? (
            <>
              {/* 取款货币 */}
              <div className={deposit_input_cn.item}>
                <span className={deposit_input_cn.label}>{text('text_66')}</span>
                <input autoComplete='off' name='huobi' className={deposit_input_cn.input} disabled defaultValue='USDT(TRC20)' />
              </div>
              {/* 取款地址 */}
              <div className={class_esy([deposit_input_cn.item, 'cursor-pointer'])} onClick={onOpen}>
                <span className={deposit_input_cn.label}>{text('text_67')}</span>
                <input
                  autoComplete='off'
                  name='usdt-addr'
                  readOnly
                  className={class_esy([deposit_input_cn.input, 'cursor-pointer'])}
                  value={addr}
                  onChange={(e) => {
                    setAddr(e.target.value);
                  }}
                />
                <span className={deposit_input_cn.suffix}>
                  {bindInfo ? (
                    <RightOutlined className='text-xs text-color-21' />
                  ) : (
                    <button type='button' className='py-1 px-3 bg-color-21 text-white rounded-3xl cursor-pointer' onClick={addBandAccount}>
                      {text('text_64')}
                    </button>
                  )}
                </span>
              </div>
            </>
          ) : null}
          {isBank ? (
            <>
              {/* 真实姓名 */}
              <div className={deposit_input_cn.item}>
                <span className={deposit_input_cn.label}>
                  {text('text_55')}
                  <WarnCircleFilled className='text-sm text-color-21 ml-0.5' />
                </span>
                <input autoComplete='off' name='username' className={deposit_input_cn.input} disabled defaultValue={Name} />
              </div>
              {/* 银行账号 */}
              <div className={class_esy([deposit_input_cn.item, 'cursor-pointer'])} onClick={onOpen}>
                <span className={deposit_input_cn.label}>{text('text_56')}</span>
                <input
                  autoComplete='off'
                  name='bank-number'
                  readOnly
                  className={class_esy([deposit_input_cn.input, 'cursor-pointer'])}
                  value={bank}
                  onChange={(e) => {
                    setBank(e.target.value);
                  }}
                />
                <span className={deposit_input_cn.suffix}>
                  {bindInfo ? (
                    <RightOutlined className='text-xs text-color-21' />
                  ) : (
                    <button type='button' className='py-1 px-3 bg-color-21 text-white rounded-3xl cursor-pointer' onClick={addBandAccount}>
                      {text('text_65')}
                    </button>
                  )}
                </span>
              </div>
            </>
          ) : null}
          {/* 取款金额 */}
          <div className={deposit_input_cn.item}>
            <span className={deposit_input_cn.label}>{text('text_57')}</span>
            <input
              name='amont'
              className={class_esy([deposit_input_cn.input, 'rounded-b-none'])}
              autoComplete='off'
              readOnly={channel?.AmountLimitType === 1}
              value={amont}
              maxLength={24}
              onChange={(e) => {
                const v = e?.target?.value || '';
                if (channel?.MaxAmount && v >= channel?.MaxAmount) {
                  setValue(channel?.MaxAmount);
                } else {
                  setValue(v);
                }
              }}
              onBlur={() => {
                // 极值控制
                if (channel?.MaxAmount && amont > channel?.MaxAmount) {
                  setValue(channel?.MaxAmount);
                } else if (amont && channel?.MinAmount && amont < channel?.MinAmount) {
                  setValue(channel?.MinAmount);
                }
              }}
              placeholder={`${channel?.MinAmount}${text('text_52')}~${channel?.MaxAmount}${text('text_52')}`}
            />
            <span className={deposit_input_cn.suffix}>RMB</span>
            <div className='border-r border-b border-l border-solid border-color-19 px-3 rounded-b '>
              {isUST ? (
                <div className='flex items-center justify-between h-8'>
                  <div className=''>
                    {text('text_62')}
                    <span className='text-color-21 ml-4 mr-2'>{countU}</span>USDT(TRC20)
                  </div>
                  <button type='button' className='py-1 px-3 bg-color-21 text-white rounded-3xl cursor-pointer'>
                    {text('text_63')}
                  </button>
                </div>
              ) : null}
              <div className='flex items-center gap-x-1 h-8 cursor-pointer text-color-21'>
                {text('text_60')}
                <RightOutlined className='text-xs text-color-21' />
              </div>
            </div>
          </div>
          {/* 取款密码 */}
          <div className={deposit_input_cn.item}>
            <span className={deposit_input_cn.label}>{text('text_58')}</span>
            <input
              autoComplete='off'
              type={iptType}
              name='password'
              maxLength={12}
              className={deposit_input_cn.input}
              placeholder={text('text_59')}
              value={psdVal}
              onChange={(e) => {
                setPassword(e?.target?.value);
              }}
            />
            <span
              className={class_esy([deposit_input_cn.suffix], 'cursor-pointer')}
              onClick={() => {
                setIptType((preT) => (preT === 'password' ? 'text' : 'password'));
              }}
            >
              {iptType === 'password' ? <EyeHideOutlined className='text-base text-color-21' /> : <EyeOutlined className='text-base text-color-21' />}
            </span>
          </div>
        </form>
        {/* {isArray(btns) && !isEmpty(btns) ? (
          <div className='flex items-center gap-2 my-3 text-xs'>
            {btns.map((txt) => (
              <div
                key={txt}
                className={class_esy(['py-1 px-3 rounded cursor-pointer', amont === txt ? 'bg-color-21 text-white' : 'bg-body'])}
                onClick={() => {
                  setValue(txt);
                }}
              >
                {txt}
              </div>
            ))}
          </div>
        ) : null} */}
        <div className='px-3 w-full box-border fixed z-10 bottom-0 left-0 pb-2.5 bg-white'>
          <div className='text-error text-xs font-bold py-4 whitespace-pre-line'>{text('text_61')}</div>
          <Button type={isSubmit ? 'default' : 'disabled'} className='rounded' onClick={onDeposit}>
            {text('text_54')}
          </Button>
        </div>
      </div>
      <BindListDialog open={dlOpen} onClose={onClose} onSelected={onSelected} id={types[channel?.ModeId]} token={Token} onAdd={addBandAccount} />
    </div>
  );
}

function Withdraw() {
  const [data, setData] = useState([]);
  const { userInfo } = useUserInfoStore();
  const { changeState } = useGlobalStore();

  useEffect(() => {
    if (userInfo?.Token) {
      changeState('isLoading', true);
      postWithdrawlConfig({})
        .then((res: any) => {
          if (isArray(res?.Data)) {
            setData(res.Data.map((it, i) => ({ title: it.Title, paneKey: it.Id + i, contentData: it.SubList })));
          }
        })
        .catch(() => {
          setData(list);
        })
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  }, [changeState, userInfo?.Token]);

  return (
    <div className='bg-body-2 h-full flex flex-col'>
      <Header title='text_5' isGoHome />
      {isEmpty(data) ? (
        <Empty />
      ) : (
        <Tabs
          classNames={{ titles: 'relative text-base flex-nowrap bg-white', indicator: 'absolute bg-color-21 rounded-3xl transition-left-top duration-250 z-1' }}
          tabs={data}
          isDestroyUnactive
          renderTitle={<RenderTitle />}
          renderContent={<RenderContent Token={userInfo?.Token} Name={userInfo?.Name} />}
        />
      )}
    </div>
  );
}

export default observer(Withdraw);
